<!-- 出库退货管理 -->
<template>
    <div class="page-box">
        <div class="page-title">
            {{ '补库退货' }}
        </div>

        <div class="page-search">
            <div class="search-box" :style="{ height: IsHeight }">
                <el-input v-model="pageData.keywords" placeholder="出库退货单号/出库单号/客户"
                    style="width: 200px; margin-right: 10px" suffix-icon="search" @input="handleSearchChange" />

                <h3 style="margin-right: 10px;margin-left: 10px;">显示：</h3>
                <el-button :type="pageData.status === '0' ? 'primary' : ''"
                    @click="handleStatusFilter('0')">待提交</el-button>
                <el-button :type="pageData.status === '1' ? 'primary' : ''"
                    @click="handleStatusFilter('1')">审核中</el-button>
                <el-button :type="pageData.status === '2' ? 'primary' : ''"
                    @click="handleStatusFilter('2')">审核完成</el-button>
                <el-button :type="pageData.status === '3' ? 'primary' : ''"
                    @click="handleStatusFilter('3')">审核拒绝</el-button>
            </div>
            <div class="search-btn">
                <div class="btn_item" @click="handleClickHeight">
                    <img class="btn_img" src="@/assets/sx.png" alt="" />
                    <span> 高级筛选 </span>
                </div>
            </div>
        </div>
        <div class="search-btn-right">
            <el-button color="#626aef" type="primary" @click="handleClickAdd"> 新增 </el-button>
        </div>
        <!-- 批量提交审核 -->
        <div class="batch-submit-audit" style="margin-bottom: 10px;">
            <div class="batch-info">
                已选择 {{ selectedRows.length }} 项
            </div>
            <el-button color="#626aef" type="primary" @click="handleClickSubmitAudit"
                :disabled="selectedRows.length === 0">
                批量提交审核 ({{ selectedRows.length }})
            </el-button>
        </div>

    </div>


    <div class="table-box">
        <el-table :data="tabeData" style="width: 100%" v-loading="loading" border
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column align="center" prop="return_order_no" label="出库退货单号" width="200" />
            <el-table-column align="center" prop="outbound_order_no" label="补库单单号" width="200" />
            <el-table-column align="center" prop="customer_name" label="客户" width="150" />
            <el-table-column align="center" prop="status" label="状态" width="100">
                <template #default="scope">
                    <el-tag :type="getStatusType(scope.row.status)" size="small">
                        {{ scope.row.status_text }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="manager_name" label="退货负责人" width="120" />
            <el-table-column align="center" prop="manager_phone" label="负责人电话" width="130" />
            <el-table-column align="center" prop="creator_name" label="创建人" width="100" />
            <el-table-column align="center" prop="created_at" label="创建时间" width="160" />
            <el-table-column align="center" prop="return_date" label="退货日期" width="160" />
            <el-table-column fixed="right" label="操作" min-width="270" prop="id" align="center">
                <template #default="scope">
                    <div class="btn-box">
                        <el-button plain size="small" type="primary" @click="handleClickEdit(scope.row)"> 编辑
                        </el-button>
                        <el-button plain size="small" type="danger" @click="handleClickDelete(scope.row)"> 删除
                        </el-button>
                        <el-button plain size="small" type="warning"
                            @click="handleClickSubmitSingleAudit(scope.row)">审核</el-button>
                        <el-button plain size="small" type="info" @click="handleClickDetails(scope.row)">详情</el-button>

                    </div>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <!-- 分页 -->
    <Pagination class="pagination" @pageSize="pageSize" @getPage="getPage" :page="pageData.page"
        :page-size="pageData.pageSize" :total="total" />
    <!-- 新增出库 -->
    <ReturnFormAdd ref="AddedOutboundRef" @refresh="getAlltabeData" />
    <!-- 补库单详情抽屉 -->
    <ReturnFormDetails v-model:dialogVisible="DetailsOutboundOrderVisible" :dialogRow="dialogRow" />
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import { useRouter } from "vue-router";
import { usePlatformManagementStore } from "@/stores";
import { ElMessage, ElMessageBox } from 'element-plus';
import Pagination from "@/components/Pagination.vue";
import ReturnFormAdd from "./components/OutboundReturnManagement/ReturnFormAdd.vue";
import ReturnFormDetails from "./components/OutboundReturnManagement/ReturnFormDetails.vue";
const platformManagementStore = usePlatformManagementStore();
const router = useRouter();
import api from "@/api";

//  新增出库
const AddedOutboundRef = ref<any>(null);
// 出库详情
let IsHeight = ref<number | string>(0);

//  -----------------出库详情抽屉
//  出库详情
const DetailsOutboundOrderVisible = ref<boolean>(false);

// 定义返回数据类型
interface OutboundReturn {
    id: string | number;
    return_order_no: string;
    outbound_order_no: string;
    return_amount: string | number;
    return_date: string;
    customer_name: string;
    status: number;
    status_text: string;
    manager_name: string;
    manager_phone: string;
    audit_name: string;
    creator_name: string;
    created_at: string;
    remark?: string;
    rowNumber?: number;
}

// 出库订单详情
let dialogRow = ref<OutboundReturn>({} as OutboundReturn);

//  -----------------列表数据
const pageData = ref({
    pageSize: 10,
    page: 1,
    status: "",
    keywords: "",
});

const total = ref(0);
const tabeData = ref<OutboundReturn[]>([]);
const loading = ref(false);

// 存储选中的行数据
const selectedRows = ref<OutboundReturn[]>([]);

// 处理表格选择变化
const handleSelectionChange = (selection: OutboundReturn[]) => {
    selectedRows.value = selection;
    console.log('选中的行数据:', selectedRows.value);
};

// 侦听动态分页
watch(
    () => pageData.value,
    () => {
        getAlltabeData();
    },
    { deep: true }
);

let nub = ref<number>(0);
const handleClickHeight = () => {
    nub.value++;
    if (nub.value % 2 == 1) {
        IsHeight.value = '50px';
    } else {
        IsHeight.value = '0px';
    }
}

const pageSize = (e: number) => {
    pageData.value.pageSize = e
}
const getPage = (e: number) => {
    pageData.value.page = e
}

onMounted(() => {
    getAlltabeData();
})

// 单独或批量提交审核
const handleClickSubmitAudit = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要提交审核的退货单');
        return;
    }

    // 检查选中的退货单状态是否允许提交审核
    const invalidStatusRows = selectedRows.value.filter(row => row.status !== 0);
    if (invalidStatusRows.length > 0) {
        ElMessage.warning('只有"待提交"状态的退货单才能提交审核');
        return;
    }

    try {
        // 确认操作
        await ElMessageBox.confirm(
            `确定要提交选中的 ${selectedRows.value.length} 个退货单进行审核吗？`,
            '提交审核确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        );

        // 提取选中行的ID数组
        const ids = selectedRows.value.map(row => Number(row.id));

        console.log('批量提交审核的ID数组:', ids);

        const res = await api.Outbound.submitAuditBatch({
            ids: ids
        });

        if (res.code == 200) {
            ElMessage.success(`成功提交 ${selectedRows.value.length} 个退货单进行审核`);
            // 清空选择
            selectedRows.value = [];
            // 刷新列表
            getAlltabeData();
        } else {
            ElMessage.error(res.message || '提交审核失败');
        }
    } catch (error: any) {
        if (error !== 'cancel') {
            console.error('批量提交审核失败:', error);
            ElMessage.error('网络错误，提交失败');
        }
    }
};

// 单个提交审核
const handleClickSubmitSingleAudit = async (row: OutboundReturn) => {
    if (row.status !== 0) {
        ElMessage.warning('只有"待提交"状态的退货单才能提交审核');
        return;
    }

    try {
        await ElMessageBox.confirm(
            `确定要提交退货单号为 ${row.return_order_no} 的记录进行审核吗？`,
            '提交审核确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        );

        const res = await api.Outbound.submitAuditBatch({
            ids: [Number(row.id)]
        });

        if (res.code == 200) {
            ElMessage.success('提交审核成功');
            getAlltabeData();
        } else {
            ElMessage.error(res.message || '提交审核失败');
        }
    } catch (error: any) {
        if (error !== 'cancel') {
            console.error('提交审核失败:', error);
            ElMessage.error('网络错误，提交失败');
        }
    }
};

// 获取补库退货列表
const getAlltabeData = async () => {
    loading.value = true;
    try {
        const res = await api.Outbound.getoutboundReturnList({
            ...pageData.value,
        });

        console.log('补库退货列表API返回:', res);

        if (res.code == 200) {
            // 处理数据，添加序号
            const processedData = res.data.data.map((item: any, index: number) => ({
                ...item,
                rowNumber: (pageData.value.page - 1) * pageData.value.pageSize + index + 1,
                return_amount: item.return_amount || '0.00',
                return_date: item.return_date || '--',
                customer_name: item.customer_name || '--',
                status_text: item.status_text || getStatusText(item.status),
                manager_name: item.manager_name || '--',
                manager_phone: item.manager_phone || '--',
                creator_name: item.creator_name || '--',
                created_at: item.created_at || '--',
                remark: item.remark || '--'
            }));

            tabeData.value = processedData;
            total.value = res.data.pager?.total_records || 0;
        } else {
            ElMessage.error(res.message || '获取数据失败');
        }
    } catch (error) {
        console.error('获取补库退货列表失败:', error);
        ElMessage.error('获取数据失败');
    } finally {
        loading.value = false;
    }
};

// 搜索变化处理
const handleSearchChange = () => {
    pageData.value.page = 1;
    setTimeout(() => {
        getAlltabeData();
    }, 300);
};

// 状态筛选
const handleStatusFilter = (status: string) => {
    if (pageData.value.status === status) {
        pageData.value.status = ''; // 如果点击相同状态，取消筛选
    } else {
        pageData.value.status = status;
    }
    pageData.value.page = 1;
    getAlltabeData();
};

// 获取状态文本
const getStatusText = (status: number) => {
    const statusMap: { [key: number]: string } = {
        0: '待提交',
        1: '审核中',
        2: '审核完成',
        3: '审核拒绝'
    };
    return statusMap[status] || '未知状态';
};

// 获取状态标签类型
const getStatusType = (status: number) => {
    const statusTypeMap: { [key: number]: string } = {
        0: 'info',     // 待提交
        1: 'warning',  // 审核中
        2: 'success',  // 审核完成
        3: 'danger'    // 审核拒绝
    };
    return statusTypeMap[status] || 'info';
};

//  新增出库退货
const handleClickAdd = () => {
    AddedOutboundRef.value?.openLoading();
}

// 编辑
const handleClickEdit = async (row: OutboundReturn) => {
    try {
        const res = await api.Outbound.getoutboundReturnDetails({ id: row.id });
        if (res.code == 200) {
            AddedOutboundRef.value?.openLoading(res.data);
        } else {
            ElMessage.error(res.message || '获取详情失败');
        }
    } catch (error) {
        console.error('获取退货单详情失败:', error);
        ElMessage.error('获取详情失败');
    }
};

// 删除
const handleClickDelete = (row: OutboundReturn) => {
    ElMessageBox.confirm(
        `确定要删除退货单号为 ${row.return_order_no} 的记录吗？`,
        '删除确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        try {
            const res = await api.Outbound.deleteoutboundReturn({ id: row.id });
            if (res.code == 200) {
                ElMessage.success('删除成功');
                getAlltabeData();
            } else {
                ElMessage.error(res.message || '删除失败');
            }
        } catch (error) {
            console.error('删除失败:', error);
            ElMessage.error('删除失败');
        }
    }).catch(() => {
        // 用户取消删除
    });
};

// 审核
const handleClickAudit = (row: OutboundReturn) => {
    console.log('审核退货单:', row);
    // TODO: 实现审核功能
    ElMessage.info('审核功能开发中...');
};

// 提交审核
const handleSubmitAudit = () => {
    console.log('批量提交审核');
    // TODO: 实现批量提交审核功能
    ElMessage.info('批量提交审核功能开发中...');
};

//  打开出库详情抽屉
const handleClickDetails = async (row: OutboundReturn) => {
    try {
        console.log('打开退货单详情:', row);

        // 获取退货单详情
        const res = await api.Outbound.getoutboundReturnDetails({ id: row.id });

        if (res.code == 200) {
            console.log('退货单详情数据:', res.data);

            // 打开详情抽屉并传递数据
            DetailsOutboundOrderVisible.value = true;
            dialogRow.value = {
                ...res.data,
                // 确保关键字段存在
                id: res.data.id || row.id,
                return_order_no: res.data.return_order_no || row.return_order_no,
                outbound_order_no: res.data.outbound_order_no || row.outbound_order_no,
                return_amount: res.data.return_amount || row.return_amount,
                return_date: res.data.return_date || row.return_date,
                customer_name: res.data.customer_name || row.customer_name,
                status: res.data.status !== undefined ? res.data.status : row.status,
                status_text: res.data.status_text || row.status_text,
                manager_name: res.data.manager_name || row.manager_name,
                manager_phone: res.data.manager_phone || row.manager_phone,
                creator_name: res.data.creator_name || row.creator_name,
                created_at: res.data.created_at || row.created_at,
                note: res.data.note || res.data.remark || '',
                // API返回的其他字段
                return_discount: res.data.return_discount || '0.00',
                outbound_order_id: res.data.outbound_order_id,
                customer_id: res.data.customer_id,
                manager_member_id: res.data.manager_member_id,
                audit_name: res.data.audit_name || '',
                audited_at: res.data.audited_at || '',
                audit_note: res.data.audit_note || '',
                creator_admin_id: res.data.creator_admin_id || ''
            };

            console.log('传递给详情组件的数据:', dialogRow.value);
        } else {
            ElMessage.error(res.message || '获取退货单详情失败');
        }
    } catch (error) {
        console.error('获取退货单详情失败:', error);
        ElMessage.error('获取退货单详情失败');
    }
};
</script>

<style lang="scss" scoped>
.btn-box {
    display: flex;
    align-items: center;
    justify-content: center;
}

// 输入框样式
::v-deep .el-input__wrapper {
    background-color: rgba(250, 252, 251, 1);
}

//表格样式

::v-deep .el-table {
    --el-table-header-bg-color: rgba(235, 236, 240, 1);
}

::v-deep .el-table thead {
    color: #444;
}

//分页样式
.pagination {
    width: calc(100% - 250px);
    position: fixed;
    bottom: 20px;
    right: 20px;
    padding-top: 10px;
    border-top: 1px solid #98989848;


}

::v-deep .el-pagination.is-background .el-pager li.is-active {
    background-color: #000 !important;
}
</style>
